package middleware

import (
	"blog/config"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type Claims struct {
	UserName string `gorm:"type:varchar(200);" json:"user_name"`
	Password string `gorm:"type:varchar(200);" json:"password"`
	jwt.StandardClaims
}

// GenerateToken 生成token
func GenerateToken(name string, pwd string) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(config.ExpireTime)

	myClaims := Claims{
		UserName: name,
		Password: pwd,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), // 过期时间
			Issuer:    "chat_gin",        // token签发人
		},
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, myClaims)
	return tokenClaims.SignedString(config.MySecret)
}

// ParseToken 校验token是否有效
func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (i interface{}, err error) {
		return config.MySecret, err
	})

	if err != nil {
		return nil, err
	}

	if myClaims, ok := token.Claims.(*Claims); ok && token.Valid {
		return myClaims, nil
	}
	return nil, errors.New("无效token")
}

// TokenExpired 定义错误
var (
	TokenExpired = errors.New("token已过期,请重新登录。")
)

func JwtToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		// 查看token信息为空的情况
		tokenHeader := c.Request.Header.Get("Authorization")
		fmt.Println("开始鉴权", tokenHeader)
		if tokenHeader == "" {
			code = config.ErrorTokenExist
			c.JSON(http.StatusOK, gin.H{
				config.ResStatus: code,
				config.ResMsg:    config.GetErrMsg(code),
			})
			c.Abort()
			return
		}
		fmt.Println("tokne不是空的")

		// 解析token是否有效
		_, err := ParseToken(tokenHeader)
		fmt.Println("鉴权结果", err)
		if err != nil {
			fmt.Println("校验token失败", err)
			if errors.Is(err, TokenExpired) {
				c.JSON(http.StatusOK, gin.H{
					config.ResStatus: config.ERROR,
					config.ResMsg:    config.GetErrMsg(config.ErrorTokenRuntime),
				})
				c.Abort()
				return
			}
			// 其他错误
			c.JSON(http.StatusOK, gin.H{
				config.ResStatus: config.ERROR,
				config.ResMsg:    err.Error(),
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
